module file;

//import std.string, std.container, std.c.time;
//import win32.windows;

import std.c.stdio; // : fopen, fclose, fread, fgets, fwrite, fflush, fseek, ftell, feof, ferror, FILE;
//import std.stdio : sprintf;
//import std.ctype: toupper;

class CFile
{
public:
	FILE *m_pFile;

	this()
	{
		m_pFile = null;
	}
	
	~this()
	{
		if ( m_pFile )
			Close();
	}

	bool Open( const char[] pFile, const char[] pMode )
	{
		if ( m_pFile )
			return false;

		m_pFile = fopen( pFile.ptr, pMode.ptr );

		return m_pFile ? true : false;
	}
	
	void Close()
	{
		if ( m_pFile )
		{
			fclose( m_pFile );
			m_pFile = null;
		}
	}
	
	int Read( char[] pBuf, int nBufLen )
	{
		return fread( pBuf.ptr, 1, nBufLen, m_pFile );
	}
	
	bool ReadString( char[] pBuf, int nBufLen )
	{
		return fgets( pBuf.ptr, nBufLen, m_pFile ) ? true : false;
	}
	
	int Write( const char[] pBuf, int nBufLen )
	{
		return fwrite( pBuf.ptr, 1, nBufLen, m_pFile );
	}
	
	void Flush()
	{
		fflush( m_pFile );
	}
	
	bool IsEnd()
	{
		return feof( m_pFile ) ? true : false;
	}
	
	int GetLength()
	{
		int length, save;

		// Save the pointer location
		save = ftell(m_pFile);
		if (ferror(m_pFile))
			return 0;

		// Seek to end of file
		fseek(m_pFile, 0, SEEK_END);
		if (ferror(m_pFile))
			return 0;

		// Get the size of the file
		length = ftell(m_pFile);
		if (ferror(m_pFile))
			return 0;

		// Seek back to save position
		fseek(m_pFile, save, SEEK_SET);
		if (ferror(m_pFile))
			return 0;

		return length;
	}

/*public:
	// Static Helper Functions
	static bool	 IsExist( const char *pPath );
	static int   GetLength( const char *pPath );*/
}